<?php

namespace App\Http\Controllers\Api\Website;


use App\Exceptions\ApiException;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\model\BrokerMobile;
use App\Service\TeleService;
use App\Http\Resources\CallResource;

class CallController extends Controller
{
    //
    public function bindCall(Request $request,$true_mobile){
        $brokerMobile=  \Cache::remember($true_mobile,1,function(){
            return  BrokerMobile::where('is_bind',0)
                ->where('updated_at','<',Carbon::now()->addMinutes(-1))->inRandomOrder()->first();
        });
        if(!$brokerMobile){
            return new CallResource(['msg'=>"busy"]);
        }else{
            $tele= new TeleService();
            $tele->setSpInfo();
            try{
                $tele->unbindMobile($true_mobile, $brokerMobile->mobile);
            }catch (ApiException $exception){

            };
            $result=$tele->bindMobile($this->createdSeqId(), $true_mobile,$brokerMobile->mobile);
            $brokerMobile['msg'] = "ok";
            return new CallResource($brokerMobile);
        }
    }
    public function searchCall(Request $request,TeleService $teleService,$mobile){
        return $teleService->searchBindMobile($mobile);
    }

    public function unbindCall(Request $request,$true_mobile,$virtualMobile){
        $tele= new TeleService();
        $tele->setSpInfo();
        return $tele->unbindMobile($true_mobile, $virtualMobile);
    }

    protected function createdSeqId(){
        return uniqid();
    }
}
